﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using MISAPP.MISInterface;

/// <summary>
/// ViewMatrix 的摘要描述
/// </summary>
public class ViewMatrix : System.Web.UI.Page
{
    #region property
    /// <summary>
    /// 要使用的完整名稱 EX:MISAPP.Classify.Service.Service_WMG001
    /// </summary>
    protected string serviceName = "";

    protected object instance = null;

    protected object Instance
    {
        get
        {
            if (instance == null)
            {
                instance = GetServiceObject();
            }
            return instance;
        }
    }
    protected string[] criteriaList = null;

    protected ContentPlaceHolder mpContentPlaceHolder = null;

    protected string ContentPlaceHolderID = "ContentPlaceHolder1";

    Dictionary<string, System.Web.UI.UserControl> clbList = null;

    #endregion

    public ViewMatrix()
	{
        //serviceName = this.GetType().Name;
	}

    

    protected Object GetServiceObject()
    {      
        return Utility.GetServiceObject(serviceName);
    }

    /// <summary>
    /// 取回 Service 要填入到控制項 complexListBox 中的條件
    /// </summary>
    /// <param name="p_methodName"></param>
    /// <returns></returns>
    protected System.Data.DataSet GetCriteriasData(string p_methodName)
    {
        System.Reflection.MethodInfo mi = GetObjectMethodInfo(p_methodName);
        System.Data.DataSet ds = (System.Data.DataSet)DoMethodInvoke(mi,instance, null);
        return ds;
    }

    protected string[] GetCriterias()
    {
        System.Reflection.MethodInfo mi = GetObjectMethodInfo("GetCriteriaArray");
        string[] criterias = (string[])DoMethodInvoke(mi, instance, null);
        return criterias;
    }

    protected System.Reflection.MethodInfo GetObjectMethodInfo(string p_methodName)
    {
        return GetObjectMethodInfo(p_methodName,null);
    }

    protected System.Reflection.MethodInfo GetObjectMethodInfo(string p_methodName, Type[] p_paraTypes)
    { 
        return GetObjectMethodInfo(p_methodName, p_paraTypes, Instance);
    }

    protected System.Reflection.MethodInfo GetObjectMethodInfo(
        string p_methodName, Type[] p_paraTypes,object p_obj)
    {
        System.Reflection.MethodInfo mi = null;
        mi = Utility.FindMethodInfo(
              p_obj.GetType().GetMethods(),
              p_methodName, p_paraTypes);
        if (mi == null)
        {
            new Exception(string.Format("找不到{0} ", p_methodName));
        }
        return mi;    
    }

    protected System.Web.UI.UserControl FindControlInContentPlaceHolder(string p_conrolID)
    {
        if (mpContentPlaceHolder == null)
        {
            mpContentPlaceHolder = (ContentPlaceHolder)Master.FindControl(ContentPlaceHolderID);
        }
        return mpContentPlaceHolder.FindControl(p_conrolID) as System.Web.UI.UserControl;
    }

    protected int GetGridViewPageSize()
    {
        return Convert.ToInt16(Session["PageSize"]);
    }

    /// <summary>
    /// 從Utility 中的指定method 取回資料來
    /// </summary>
    /// <param name="p_methodName"></param>
    /// <returns></returns>
    protected System.Data.DataTable GetDataFromUtilityMethod(string p_methodName)
    {
        Utility uu = new Utility();
        System.Reflection.MethodInfo mi = Utility.FindMethodInfo(uu.GetType().GetMethods()
            , p_methodName, null);
        return (System.Data.DataTable)DoMethodInvoke(mi,uu, null);
    }

    /// <summary>
    /// 從Service 中指定的Method 中取回資料來
    /// </summary>
    /// <param name="p_methodName"></param>
    /// <returns></returns>
    protected System.Data.DataTable GetDataFromSerevice(string p_methodName)
    {
        FillToSession();
        Type[] paraType = new Type[] { typeof(System.Collections.ArrayList) };
        System.Reflection.MethodInfo mi = GetObjectMethodInfo(p_methodName, paraType);
        System.Data.DataTable dt =
            (System.Data.DataTable)DoMethodInvoke(
                                    mi, Instance
                                    , new object[]{(ArrayList)Session["criteriaList"]}
                                    );
        return dt;
    }

    /// <summary>
    /// 把session 中的物件統一放到ArrayList
    /// </summary>
    protected virtual void FillToSession()
    {
        ArrayList criteriaAL = new ArrayList();
        if (criteriaList == null) { return; }
        //page_load 時要去把session中的名稱放到criteriaList 這一個陣列中去
        foreach (string str in criteriaList)
        {
            criteriaAL.Add(Session[str]);
        }
        Session["criteriaList"] = criteriaAL;  
    }

    /// <summary>
    /// 目前針對 complexListBox.ascx 來做
    /// </summary>
    /// <param name="p_methodName">Service 中的Method</param>
    /// <param name="p_controlMethod"></param>
    protected virtual void FillCriteria(string p_methodName,string p_controlMethod)
    {
        System.Data.DataSet ds = GetCriteriasData(p_methodName); //CIB.GetCriteriaData();
        string[] criterias = GetCriterias(); //CIB.GetCriteriaArray();
        string strControl = "CLB_{0}";
        foreach (string str in criterias)
        {
            System.Web.UI.UserControl clb = FindControlInContentPlaceHolder(
                    string.Format(strControl, str)) as System.Web.UI.UserControl;
            if (clb != null)
            {
                object[] para = new object[] { ds.Tables[str], 0, 1 };
                Type[] paraType = new Type[] { typeof(System.Data.DataTable), typeof(Int32), typeof(Int32) };
                System.Reflection.MethodInfo m = Utility.FindMethodInfo(clb.GetType().GetMethods()
                    , p_controlMethod, paraType);
                DoMethodInvoke(m,clb, para);
            }
        }
    }

    protected virtual void FillGroupBy(string p_methodName, Control p_control)
    {
        System.Reflection.MethodInfo mi = GetObjectMethodInfo(p_methodName);
        System.Data.DataTable dt = (System.Data.DataTable)DoMethodInvoke(mi,Instance, null);
        System.Reflection.MethodInfo controlMi = GetObjectMethodInfo(
            "SetData",new Type[]{typeof(System.Data.DataTable)} , p_control);
        object[] para = new object[] { dt};
        DoMethodInvoke(controlMi, p_control, para);
    }

    protected void FillControl()
    {
        clbList = new Dictionary<string, System.Web.UI.UserControl>();
        string[] criterias = GetCriterias();
        string strControl = "CLB_{0}";
        foreach (string str in criterias)
        {
            System.Web.UI.UserControl clb = FindControlInContentPlaceHolder(
                string.Format(strControl, str)) as System.Web.UI.UserControl; ;
            if (clb != null)
            {
                clbList.Add(str, clb);
            }
        }
    }

    protected List<iSelectList> GetSelectCLB()
    {
        FillControl();
        return GetSelectList(clbList);
    }

    protected List<iSelectList> GetSelectList(Dictionary<string, System.Web.UI.UserControl> clbList)
    {
        List<iSelectList> newSL = new List<iSelectList>();
        System.Web.UI.UserControl control = null;
        iSelectList SL = null;
        foreach (KeyValuePair<string, System.Web.UI.UserControl> clb in clbList)
        {
            SL = Utility.GetServiceObject("MISAPP.Classify.Service.SelectList") as iSelectList;
            control = clb.Value as System.Web.UI.UserControl;
            System.Reflection.MethodInfo mi = GetObjectMethodInfo(
                "GetSelectList"
                , new Type[]{typeof(System.String),typeof(object)} 
                , control);
            if (mi != null)
            {
                SL = DoMethodInvoke(mi, control, new object[] { clb.Key, SL })
                                as MISAPP.Classify.Service.SelectList;
                if (SL.GetListCount() > 0)
                {
                    newSL.Add(SL);
                }            
            }
        }
        return newSL;            
    }

    protected object DoMethodInvoke(System.Reflection.MethodInfo p_mi, object p_object, object[] p_value)
    {
        object rtn = null;
        try
        {
            rtn = p_mi.Invoke(p_object, p_value);
        }
        catch (Exception ex)
        {
            throw new Exception(string.Format("{0}:{1}", "DoMethodInvoke",ex.Message));
        }
        return rtn;
    }

    protected object DoMethodInvoke(System.Reflection.MethodInfo p_mi,object[] p_value)
    {
        return DoMethodInvoke(p_mi, Instance, p_value);
    }

    protected void setValueToContext(string[] p_keys, object[] p_values)
    {
        if (!p_keys.Length.Equals(p_values.Length))
        {
            throw new Exception("陣列參數不對稱  BY setValueToContext");
        }
        for (int i = 0; i < p_keys.Length; i++)
        {
            Context.Items.Add(p_keys[i], p_values[i]);
        }
    }

    protected object getValueFromContext(string p_key)
    {
        object obj = null;
        string exMSG = "View.Matrix:getValueFromContext {0}";
        try
        {
            obj = Context.Items[p_key];
        }
        catch (Exception ex)
        {
            throw new Exception(string.Format(exMSG,ex.Message));
        }
        return obj;
    }

    /// <summary>
    /// 取得所設定的使用者TEAM EX:CIB、WMG, 位置0:id,位置1:lvevl,位置2:team
    /// </summary>
    /// <returns></returns>
    protected string getResultValue(int p_pos)
    { 
        List<string> result = Session["result"] as List<string>;
        return result[p_pos];
    }

    protected void limit()
    {
        bool ok = false;    
        string className = this.ToString().Replace("ASP.view_", "")
            .Replace("_aspx", "").ToUpper();
        className = className.Substring(0, className.IndexOf('_'));
        List<string> result = Session["result"] as List<string>;
        for (int i = 2; i < result.Count; i++)
        {
            if (className.Equals(result[i]))
            {
                ok = true;
                break;
            }
        }
        string pth = HttpContext.Current.Request.ApplicationPath;
        if (ok == false)
        { 
            Server.Transfer("../MIS/Default.aspx"); 
            //Server.Transfer(HttpRuntime.AppDomainAppVirtualPath+ "/MIS/Default.aspx" ); 
            
        }
        //Response.Redirect
    }
}
